// 这个模块实现了静态文件的路由分发。注意，该路由仅限于用来测试，生产
// 环境使用 Nginx 作为静态文件的路由分发。

import { Router } from '../router'
import { IncomingMessage } from '../server'
import { cond, BadRequestError, UnauthorizedError } from '../error'
import conf from '../config'
import * as GitHub from 'github-api'
import * as http from 'http'
import * as fs from 'fs'
import * as path from 'path'

// TODO: 静态路由仅限于测试，产品环境使用 Nginx
var router = new Router()
export default router

async function onStatic(req: IncomingMessage, res: http.ServerResponse, 
                        publicdir: string, contentType: string) {
  var pathname = path.join(publicdir, decodeURI(req.uri.pathname));
  await new Promise(function (complete, fail) {
    fs.stat(pathname, (err, stats) => {
      if (err || !stats.isFile()) {
        res.writeHead(404);
        res.end();
      } else {
        var rmtime = req.headers["if-modified-since"] 
                     ? (new Date(req.headers["if-modified-since"])).getTime() 
                     : 0;
        var fmtime = new Date(stats.mtime.toString()).getTime();
        if (fmtime - rmtime > 0) { 
          res.writeHead(200, {
            "cache-control" : "max-age=31536000",
            "last-modified" : stats.mtime.toString(),
            "content-type"  : contentType
          });
          fs.createReadStream(pathname).pipe(res);
        } else {
          res.writeHead(304, {
            "cache-control" : "max-age=31536000",
            "content-type"  : contentType
          });
          res.end();
        }
      }
    });
  });
}

router.get("/:path*/:name.js", async function (req, res) {
  await onStatic(req, res, conf.public, "application/javascript");
});

router.get("/:path*/:name.css", async function (req, res) {
  await onStatic(req, res, conf.public, "text/css");
});

router.get("/:path*/:name.png", async function (req, res) {
  await onStatic(req, res, conf.public, "image/png");
});

